package org.deng.learn.dubbo.consumer;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import org.deng.learn.dubbo.api.service.IUserService;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 邓力宾
 * @Desc
 * @since 2020/6/17 上午9:58
 */
public class ConsumerClient {
    /**
     * 根据URL构建一个服务
     * @param url
     * @return
     */
    public IUserService buildRemoteService(String url){
        // 引用配置
        ReferenceConfig<IUserService>  referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(IUserService.class);
        referenceConfig.setUrl(url);
        referenceConfig.setApplication(new ApplicationConfig("appClient-1"));
        return referenceConfig.get();

    }

    /**
     * 指定注册中心，自动实现负载
     * @return
     */
    public IUserService buildRemoteServiceByMulticast(){
        // 引用配置
        ReferenceConfig<IUserService>  referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(IUserService.class);
        // 指定注册中心 广播 从广播中获取注册中心注册的服务，同一个服务有多个，可实现负载
        referenceConfig.setRegistry(new RegistryConfig("multicast://224.1.2.3:11111"));
        referenceConfig.setApplication(new ApplicationConfig("appClient-1"));
        referenceConfig.setLoadbalance("roundrobin"); // 负载策略：轮循， 默认随机
        return referenceConfig.get();

    }

    private static String read() throws IOException {
        byte[] buf = new byte[1024];
        int len = System.in.read(buf);
        return new String(buf, 0, len);
    }

    public static void test1() throws IOException {
        // 多个相同服务，手动实现负载
        String url1 = "dubbo://127.0.0.1:20880/org.deng.learn.dubbo.api.service.IUserService";
        String url2 = "dubbo://127.0.0.1:20881/org.deng.learn.dubbo.api.service.IUserService";
        String url3 = "dubbo://127.0.0.1:20882/org.deng.learn.dubbo.api.service.IUserService";
        ConsumerClient client = new ConsumerClient();
        List<IUserService> list = new LinkedList<>();
        list.add(client.buildRemoteService(url1));
        list.add(client.buildRemoteService(url2));
        list.add(client.buildRemoteService(url3));
        int index = 0;
        while (!"exit".equalsIgnoreCase(read())){
            System.out.println(list.get(index).get(index));
            index++;
            if(index >= list.size()){
                index = 0;
            }
        }
    }

    /**
     * 从广播中获取暴露的服务
     * @throws IOException
     */
    public static void test2() throws IOException {

        ConsumerClient client = new ConsumerClient();
        IUserService userService = client.buildRemoteServiceByMulticast(); // 有多个，可以实现负载
        while (!"exit".equalsIgnoreCase(read())){
            System.out.println(userService.get(1));

        }
    }

    public static void main(String[] args) throws IOException {
        //test1();
        test2();
    }
}
